//join.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var uid = 0;
var token = '';
const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});

Page({
  data: {
    util: util,
    
    tc: 0,
    uid: 0, //当前登录用户Id
    token: '', //post请求时，当前登录用户token
    authData: {}, //未认证
    cataType: '',

    colorSet: '',

    chooseAddr: '',

    shopInfo: '',

    org_info: '',
    tel: '',
    phone: '',

    showAuthView: false,
    authToastData: '',

    maxImgCount: 5,
    uploadImg: [],
    imgWH: 60,
  },

  uploadParams: '',

  wxAuthFail: true,
  inviteuid: '',


  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  onLoad: function(options) {
    var that = this;
    
    var tc = app.get_tc();

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          imgWH: (res.windowWidth - 30) / 5 - 12
        });
      }
    })

    let title = options.title ? options.title : '加入我们';
    wx.setNavigationBarTitle({
      title: title,
    })

    // 10: 咨客  11:优惠券核销员  20: 经销商  30: 供货商   40:会员   50:医生  60: 美容师
    // 8：老板   80：采购员  81:管理员   9: 一级分销商  90: 二级分销商
    var catatype = options.type;
    this.setData({
      tc: tc,
      cataType: catatype
    });

    this.inviteuid = options.inviteuid ? options.inviteuid : '';

    this.showAuthView(false, true);

    //获取绑定orgid信息
    // app.getOrgInfo(function(res) {
    //   var tel_num = res.bindOrgInfo.has_app ? res.bindOrgInfo.has_app : res.dataOrgInfo.has_app;
    //   var phone_num = res.bindOrgInfo.phone ? res.bindOrgInfo.phone : res.dataOrgInfo.phone;
    //   that.setData({
    //     org_info: res,
    //     tel: tel_num ? tel_num : '',
    //     phone: phone_num ? phone_num : ''
    //   })
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
  },
  //设置titlebar 样式
  resetNavColor: function() {
    var bg_color = '#f0f0f0';
    var fg_color = '#000000';
    if (this.data.colorSet) {
      bg_color = this.data.colorSet.titlebg;
      fg_color = this.data.colorSet.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  //获取用户认证状态
  getAuth: function(uid, token) {
    var that = this;

    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getUserAuth",
        uid: uid,
        catatype: that.data.cataType,
        privatekey: privatekey
      },
      method: 'GET',
      success: function(responseData) {
        var data = responseData.data;
        console.log("已提交的认证信息：", data);
        if (data && data.res != false && data.realname) {
          //图片数据
          var oldImages = [];
          //兼容老数据
          if (data.photo){
            var iden_z = {};
            iden_z.path = data.photo;
            iden_z.url = data.photo;
            oldImages.push(iden_z);
          }
          if(data.photo2){
            var iden_b = {};
            iden_b.path = data.photo2;
            iden_b.url = data.photo2;
            oldImages.push(iden_b);
          }
          if(data.zhizhao){
            var yyzz_p = {};
            yyzz_p.path = data.zhizhao;
            yyzz_p.url = data.zhizhao;
            oldImages.push(yyzz_p);
          }
          
          //新数据的图片处理
          if(data.photos && data.photos.length > 0){
            var imgs = data.photos.split(',');
            for(var i = 0; i < imgs.length; i++){
              var imgOb = {};
              imgOb.path = imgs[i];
              imgOb.url = imgs[i];
              oldImages.push(imgOb);
            }
          }

          //所在地信息
          var addrPoint = {};
          addrPoint.address = data.address;
          addrPoint.latitude = data.lat; //纬度
          addrPoint.longitude = data.lon; //经度
          //读取门店信息
          if(data.shopid){
            app.GetUserInfo(data.shopid, function (res) {
              res.username = res.uname;
              that.setData({
                shopInfo: res
              });
            });
          }
          that.setData({
            authData: data,
            chooseAddr: addrPoint,
            uploadImg: oldImages
          });
        } else {
          that.setData({
            authData: null
          });
        }
      }
    });
  },

  //上传认证图片 
  uploadImgs: function () {
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    })
    var that = this;
    var photos = this.data.uploadImg;
    if (photos && photos.length > 0) {
      var uploadCount = 0;
      var tempFileCount = photos.length;
      for (var photoi = 0; photoi < tempFileCount; photoi++) {
        var imgInfo = photos[photoi];
        if (imgInfo.url) {
          uploadCount++;
          if (uploadCount == tempFileCount) {
            that.setData({
              uploadImg: photos
            });
            console.log("图片完整信息：", that.data.uploadImg);
            that.uploadRichImgs();
            return;
          }
          continue;
        }
        var imageSrc = imgInfo.path;
        var nowd = new Date();
        var imgName = imageSrc.split('_')[1];
        var imgUrl = '/' + util.upyun_imgRootName + '/' + this.data.uid + '/' + imgName;

        upyun.upload({
          localPath: imageSrc,
          remotePath: imgUrl,
          success: function (res) {
            uploadCount++;

            var resImgInfo = JSON.parse(res.data);
            var resImgUrlPaths = resImgInfo.url.split('/');
            var resImgName = resImgUrlPaths[resImgUrlPaths.length - 1];
            for (var imgIndex = 0; imgIndex < tempFileCount; imgIndex++) {
              var imgPath = photos[imgIndex].path;
              if (imgPath.indexOf(resImgName) > 0) {
                photos[imgIndex].url = util.upyun_imgHost + resImgInfo.url;
                break;
              }
            }
            if (uploadCount == tempFileCount) {
              that.setData({
                uploadImg: photos
              });
              console.log("图片完整信息：", that.data.uploadImg);
              that.commitData();
            }
          },

          fail: function ({
            errMsg
          }) {
            uploadCount++;
            if (uploadCount == tempFileCount) {
              that.setData({
                uploadImg: photos
              });
              console.log("图片完整信息：", uploadImg);
              that.commitData();
            }

          }
        })
      }
    } else {
      that.commitData();
    }
  },

  //填写资料提交
  joinSubmit: function(e) {
    var that = this;
    var uid = e.detail.value.uid;
    var realName = e.detail.value.name;
    var token = e.detail.value.token;
    var mobile = e.detail.value.mobile;
    var lat = '';
    var lon = '';
    var address = '';
    var shopid = '';
    var message = e.detail.value.msg ? e.detail.value.msg : '';
    var privatekey = utilMd5.hexMD5(uid + 'userauth' + token);
    if (!realName) {
      app.dialog('请填写姓名', 'loading');
      return;
    }
    if (!mobile) {
      app.dialog('请填写手机号码', 'loading');
      return;
    }

    if (that.data.cataType == 10 || that.data.cataType == 11 || that.data.cataType == 50 || that.data.cataType == 60 || that.data.cataType == 8 || that.data.cataType == 81) {
      if (!that.data.shopInfo) {
        if (util.orgid == '25354') {
          app.dialog('请选择所属门诊', 'loading');
        } else {
          app.dialog('请选择所属门店', 'loading');
        }
        return;
      }
      shopid = that.data.shopInfo.uid;
    } else if (that.data.cataType == 20 || that.data.cataType == 30) {
      if (!that.data.chooseAddr || !that.data.chooseAddr.address) {
        app.dialog('请选择所在地', 'loading');
        return;
      }
      lat = that.data.chooseAddr.latitude;
      lon = that.data.chooseAddr.longitude;
      address = that.data.chooseAddr.address;
    }

    if (that.data.cataType == 9 || that.data.cataType == 10 || that.data.cataType == 11 || that.data.cataType == 50 || that.data.cataType == 60 || that.data.cataType == 90) {
      if (that.data.uploadImg.length <= 0) {
        app.dialog('请上传证明资料', 'loading');
        return;
      }
    }

    that.uploadParams = {
      publickey: util.publiccode,
      ac: "userauth",
      uid: uid,
      firstfxs: this.inviteuid,
      realname: realName,
      phone: mobile,
      catatype: that.data.cataType,
      address: address,
      shopid: shopid,
      lat: lat, //纬度
      lon: lon, //经度
      message: message,
      privatekey: privatekey
    };
    
    var cataType = that.data.cataType;
    if (cataType == 10 || cataType == 11 || cataType == 50 || cataType == 60 || cataType == 9 || cataType == 90) {
      that.uploadImgs();
    } else {
      wx.showLoading({
        title: 'loading...',
        mask: 'true'
      })
      that.commitData();
    }
  },

  commitData: function() {

    var that = this;
    //图片
    var photos = this.data.uploadImg; //选择的图片 	图片的本地文件路径列表
    that.uploadParams.photos = photos.map(function (item) {
      return item.url
    }).join(',');
    util.api({
      data: that.uploadParams,
      method: 'POST',
      success: function(responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log('提交认证信息返回：', data);
        if (data.res === true) {
          wx.showModal({
            title: '提示',
            content: '资料已提交',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })

        } else if (data.msg.indexOf('already') >= 0) {
          wx.showModal({
            title: '提示',
            content: '您已提交过申请资料',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '提交失败，请稍后重试',
            showCancel: false,
          })
        }
      }
    });

  },

  //获取会员介绍 和 特权 文字
  getHuiyuanNotice: function() {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "groupcontent"
      },
      method: 'GET',
      success: function(responseData) {

      }
    });
  },
  

  selectShop: function() {
    var path = "/pages/select_shop/select_shop?selshop=true"
    wx.navigateTo({
      url: path,
    })
  },
  setSelectShop: function(shop_info) {
    this.setData({
      shopInfo: shop_info
    })
  },

  selectAddress: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log("选择地址：", res);
        that.setData({
          chooseAddr: res
        })
      },
    })
  },

  makeCallPhone: function(e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function(e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function(e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },


  userCancelAuth: function() { //用户取消授权
    this.hiddenAuthView();
    wx.navigateBack({
      delta: 1
    })
  },
  showAuthView: function(showCancel, reAuth) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("已授权列表：", res);
        var authStatus_userInfo = res.authSetting["scope.userInfo"];
        if (authStatus_userInfo) {
          that.getLoginUserInfo();
        } else if (app.getShowAuthViewSign() || reAuth) {
          var authToastOb = {};
          authToastOb.showCancel = showCancel;
          authToastOb.msg = app.getBindOrgName() + " 需要您的授权"
          that.setData({
            showAuthView: true,
            authToastData: authToastOb
          })
        }
      }
    });
  },
  hiddenAuthView: function() {
    this.setData({
      showAuthView: false
    })
  },
  loginUserInfo: function(res) {
    if (res.detail.encryptedData) { //如果包含有这个字段，说明用户授权了
      this.getLoginUserInfo();
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },

  getLoginUserInfo: function() {
    var that = this;
    //读取登录用户信息
    app.LoginUserInfo(function(res) {

      if (res && res != -1) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
        })
        uid = res.uid;
        token = res.token;
        //获取认证状态
        that.getAuth(uid, token);
      }

    }, that.inviteuid);
  },



  //选择图片
  selectLocalImg: function () {
    var that = this;
    var photos = this.data.uploadImg;
    var maxCount = this.data.maxImgCount;
    wx.chooseImage({
      count: (maxCount - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        console.log("本地图片缓存路径：", tempFilePaths);
        var selImgs = [];
        for (var i = 0; i < tempFilePaths.length; i++) {
          var imgInfo = {};
          imgInfo.path = tempFilePaths[i];
          selImgs[i] = imgInfo;
        }
        if (photos.length > 0) {
          that.setData({
            uploadImg: photos.concat(selImgs)
          })
        } else {
          that.setData({
            uploadImg: selImgs
          })
        }
      },

      fail: function ({
        errMsg
      }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },

  //删除图片 
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  }

})